<!--附件表-->
<template>
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height: 60px;font-size:20px;">附件表</span>
    <el-button @click="beforeAddAttachment" type="primary" style="float:right;margin-top:13px;">
      新建文件
    </el-button>
  </div>
  <el-dialog :title="dialogTitle" v-model="dialogVisible"
             style = "width:1000px;padding:40px;" :before-closee="handleClose">
    <el-form label-width="80px" lable-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="文件名称">
            <el-input placeholder="请输入内容" v-model="saveAttachmentForm.fileName"></el-input>
          </el-form-item>
        </el-col>
          <el-col :span="12">
            <el-form style="width: 300px;margin-left: 100px">
              <el-form-item>
                <el-upload
                    class="upload-demo"
                    action="http://localhost:9090/file/uploadd"
                    :headers="{ 'Authorization': token }"
                    :data="{ category: 'documents' }"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :limit="5"
                    multiple
                >
                  <el-button type="primary">点击上传文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">支持最大 500MB 的 PDF/Word 文件</div>
                  </template>
                </el-upload>

              </el-form-item>
            </el-form>
          </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="文件类型">
            <el-select v-model="saveAttachmentForm.fileType" placeholder="请选择">
              <el-option
                  v-for="item in fileTypeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="上传人id">
            <el-input placeholder="请输入内容" v-model="saveAttachmentForm.uplinkId"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上传日期">
            <el-date-picker type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            v-model="saveAttachmentForm.uploadDate"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="创建日期">
            <el-date-picker type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            v-model="saveAttachmentForm.createTime"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="更新时间">
            <el-date-picker type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            v-model="saveAttachmentForm.updateTime"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveAttachment">确定</el-button>
    </template>
  </el-dialog>
  <!-- 楼宇搜索卡片 -->
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="文件名称">
        <el-input placeholder="请输入内容" style="width:220px;"
                  v-model="searchAttachmentForm.id" @keydown.enter="loadAttachment"></el-input>
      </el-form-item>
      <el-form-item label="文件类型">
        <el-select placeholder="请选择" style="width:220px;"
                   v-model="searchAttachmentForm.fileType">
          <el-option v-for="item in fileTypeArr"
                     :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadAttachment">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 楼宇列表 -->
  <el-card style="margin:20px;">
    <el-table :data="attachmentArr" @selection-change="handleSelectionChange">
      <!-- 添加选择列 -->
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="id" label="附件id" width="150" align="center"/>
      <el-table-column prop="fileName" label="文件名称" width="150" align="center"/>
      <el-table-column prop="fileType" label="文件类型" width="150" align="center"/>
      <el-table-column prop="uploadDate" label="上传日期" width="150" align="center"/>
      <el-table-column prop="uplinkId" label=上传人id width="150" align="center"/>
      <el-table-column prop="createTime" label="申请创建时间" width="200" align="center"/>
      <el-table-column prop="updateTime" label="更新时间，自动更新" width="200" align="center"/>

      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="editAttachment(scope.row.id)">编辑</el-button>
          <el-button link type="primary" size="small" @click="deleteAttachment(scope.row.id)">删除</el-button>
          <el-button link type="primary" size="small" @click="downloadAttachment(fileId)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

</template>
<script setup>
import { ref, onMounted } from 'vue';
import qs from "qs";
import axios from "axios";
import { ElMessage } from 'element-plus';

// 控制新增楼宇弹窗是否显示
const dialogVisible = ref(false);
// 定义变量控制dialog的标题
const dialogTitle = ref('新增实体资产');

const fileTypeArr = ref([
  { value: '.docx', label: '.docx' },
  { value: '.pdf', label: '.pdf' },
  { value: '.txt', label: '.txt' },
  { value: '.jpeg/.jpg', label: '.jpeg/.jpg' },
  { value: '.png', label: '.png' },
  { value: '.gif', label: '.gif' },
  { value: '.bmp', label: '.bmp' },
  { value: '.mp4', label: '.mp4' },
  { value: '.avi', label: '.avi' },
  { value: '.mov', label: '.mov' },
  { value: '.mkv', label: '.mkv' },
  { value: '.mp3', label: '.mp3' },
  { value: '.zip', label: '.zip' },
  { value: '.rar', label: '.rar' }
]);

const saveAttachmentForm = ref({
  id:'',
  fileName:'',
  fileType:'',
  filePath:'',
  uploadDate:'',
  uplinkId:'',
  createTime:'',
  updateTime:''
});

// 定义对象用来保存楼宇搜索条件
const searchAttachmentForm = ref({id:'',fileType:''});
// 定义数组用来保存楼宇列表表格数据
const attachmentArr = ref([]);

// 定义查询的方法
const loadAttachment = () => {
  let data =qs.stringify(searchAttachmentForm.value);
  axios.get(BASE_URL+'/v1/attachment/select?'+data).then((response)=>{
    if (response.data.code === 2000){
      attachmentArr.value = response.data.data;
    }else {
      ElMessage.error(response.data.msg);
    }
  })

};

// 一进入页面立即加载资产数据
onMounted(() => {
  loadAttachment();
});


// 定义重置搜索的方法
const resetSearch = () => {
  searchAttachmentForm.value = {};
  loadAttachment();
};

// 打开新增或编辑楼宇对话框
const  beforeAddAttachment = () => {
  dialogTitle.value = '新增文件';
  dialogVisible.value = true;
  Object.assign(saveAttachmentForm.value, {
    id:'',
    fileName:'',
    fileType:'',
    filePath:'',
    uploadDate:'',
    uplinkId:'',
    createTime:'',
    updateTime:''
  });
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
};

// 保存资产信息
const saveAttachment = () => {
  let data = qs.stringify(saveAttachmentForm.value);
  axios.post(BASE_URL+'/v1/attachment/save',data).then((response)=>{
    if(response.data.code===2000){
      ElMessage.success("保存成功!");
      saveAttachmentForm.value={};
      dialogVisible.value = false;
      loadAttachment();
    }else{
      ElMessage.error("资产名称不允许重置")
    }
  })
};
const fileList = ref([]);
const  dialogImageUrl = ref('');
const dialogVisibles = ref(false);
const actionUrl = ref(BASE_URL+'/v1/file/uploadd');
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL + '/v1/attachment/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
/**图片上传相关代码结束**/
const saveAvatar = () => {
  if (fileList.value.length === 0) {
    errorInfo('请选择文件');
    return;
  }
  let data = qs.stringify({
    id: id,
    avatar: fileList.value[0].response.data
  })
  ElMessageBox.confirm('确认保存吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    axios.post(BASE_URL + '/v1/attachment/save', data)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('保存成功!');
            store.dispatch('updateAvatar', fileList.value[0].response.data);
            fileList.value = [];
            findAll(id)
            activeName.value = 'second';
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
            })
          }
        })
  }).catch(() => {
    Info('已取消保存');
  });
}

const editAttachment = (id) => {
  dialogTitle.value = '编辑资产';
  dialogVisible.value = true;

  axios.get(BASE_URL+'/v1/attachment/select?id='+id).then((response)=>{
    if (response.data.code===2000){
      saveAttachmentForm.value = response.data.data[0];
      loadAttachment();
    }else {
      ElMessage.error(response.data.msg);
    }
  })
};

// 删除资产信息
const deleteAttachment = (id) => {
  alert(id)
  if (confirm('您确定要删除该文件么')){
    axios.delete(BASE_URL+'/v1/attachment/delete/'+id).then((response)=>{
      if (response.data.code === 2000){
        ElMessage.success('删除成功')
        loadAttachment();
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
};
// 定义处理选择变化的方法
const handleSelectionChange = (selection) => {
  console.log('Selected buildings:', selection);
  // 这里可以实现多选操作逻辑，例如批量删除等
};


</script>